<?php
switch($do){
	case "delete":
		$d_id = isset($_REQUEST['d_id']) && !empty($_REQUEST['d_id']) ? $_REQUEST['d_id']:'';
		if($d_id){
            @DB::update("dictionary", array("isdelete" => 1), array("d_id" => $d_id));
			$affected_rows = DB::affected_rows();
		}
		if($affected_rows){
			$action_class->return_json(false,"操作成功");
		}else{
			$action_class->return_json(true,"操作失败");
		}
		break;

	case "user_move":
		$issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit']:'';
		if($issubmit){
			$user_id = isset($_REQUEST['user_id']) && !empty($_REQUEST['user_id']) ? $_REQUEST['user_id']:'';
			$dept_id = isset($_REQUEST['deptId']) && !empty($_REQUEST['deptId']) ? $_REQUEST['deptId']:'';
			if(''==$dept_id){
				$action_class->return_json(true,"请选择所属部门");
			}
			if(empty($user_id)){
				$action_class->return_json(true,"请选择部门人员");
			}
			@DB::update("users", array("dept_id" => $dept_id), " user_id IN (".dimplode($user_id).") ");
			$affected_rows = DB::affected_rows();
			if($affected_rows){
				$action_class->return_json(false,"操作成功");
			}else{
				$action_class->return_json(true,"您已经在该部门");
			}
		}else{
			$tree2array_dept_option=$action_class->get_user_sub_tree2option();
			//DEBUG 获取勾选的学生
			$user_id_array = isset($_REQUEST['userIds']) && !empty($_REQUEST['userIds']) ? $_REQUEST['userIds']:'';
			include template('admin/hschool/dept_user_move');
		}
		break;

	case "add":
		$issubmit = isset($_REQUEST['dept_issubmit']) && !empty($_REQUEST['dept_issubmit']) ? $_REQUEST['dept_issubmit']:'';
		if($issubmit){
			//$d_parent_id = isset($_REQUEST['dept_parentId']) && !empty($_REQUEST['dept_parentId']) ? $_REQUEST['dept_parentId']:'';
            $d_parent_id = isset($_REQUEST['current_selected_d_id']) && !empty($_REQUEST['current_selected_d_id']) ? $_REQUEST['current_selected_d_id']:'';
			if(''==$d_parent_id){
				$action_class->return_json(true,"请选择上级部门");
			}
			$d_name = isset($_REQUEST['dept_name']) && !empty($_REQUEST['dept_name']) ? $_REQUEST['dept_name']:'';
			if(empty($d_name)){
				$action_class->return_json(true,"请输入机构名称");
			}
			$d_order = isset($_REQUEST['displayOrder']) && !empty($_REQUEST['displayOrder']) ? $_REQUEST['displayOrder']:'';
            $d_type = isset($_REQUEST['dept_d_type']) && !empty($_REQUEST['dept_d_type']) ? $_REQUEST['dept_d_type']:'';
			//DEBUG 取出父级信息
			$info_array = $action_class->get_info($d_parent_id);
			$insert_data = array(
				"d_name"=>$d_name,
				"d_parent_id"=>$d_parent_id,
				"d_order"=>$d_order,
                "d_type"=>$d_type,
				"d_level"=>($info_array['d_level']+1),
				"d_root_id"=>($info_array['d_root_id']),
				"create_time"=>TIMESTAMP,
				"modify_time"=>TIMESTAMP
			);
			$insert_id = DB::insert('dictionary',$insert_data,true);
			if($insert_id){
                //DEBUG 如果是学校 需要插入学校到学校表
                $school_type = isset($_REQUEST['school_type']) && !empty($_REQUEST['school_type']) ? $_REQUEST['school_type']:'';
                if(1==$d_type && !empty($school_type)){
                    $area = $action_class->get_tree_path_id($d_parent_id);
                    $school_data = array(
                        'd_id'=>$insert_id,
                        'school_intro'=>'',
                        'school_contact'=>'',
                        'school_grade'=>'',
                        'school_img'=>'',
                        'school_status'=>1,
                        'school_view'=>0,
                        'school_files_num'=>0,
                        'school_type'=>$school_type,
                        'school_domain'=>'',
                        'create_dateline'=>TIMESTAMP,
                        'modify_dateline'=>TIMESTAMP,
                        'area_id1' => isset($area[1]) ? $area[1]:0,
                        'area_id2'=> isset($area[2]) ? $area[2]:0,
                        'area_id3'=> isset($area[3]) ? $area[3]:0,
                    );
                    $insert_id = DB::insert('school',$school_data, true);
                }
                if($insert_id){
                    $action_class->return_json(false,"操作成功");  
                }else{
                    $action_class->return_json(true,"操作失败");
                }
			}else{
				$action_class->return_json(true,"操作失败");
			}
		}else{
			//DEBUG 取出学段信息
            require SITE_ROOT.'./source/function/function_grade_class.php';
            $pub_school_type = pub_school_type();
			include template('admin/hschool/dept_add');
		}
		break;

	case "edit":
		$issubmit = isset($_REQUEST['dept_issubmit']) && !empty($_REQUEST['dept_issubmit']) ? $_REQUEST['dept_issubmit']:'';
		if($issubmit){
			$d_id = isset($_REQUEST['dept_id']) && !empty($_REQUEST['dept_id']) ? $_REQUEST['dept_id']:'';
			$d_name = isset($_REQUEST['dept_name']) && !empty($_REQUEST['dept_name']) ? $_REQUEST['dept_name']:'';
            $d_type = isset($_REQUEST['dept_d_type']) && !empty($_REQUEST['dept_d_type']) ? $_REQUEST['dept_d_type']:0;
			$d_order = isset($_REQUEST['displayOrder']) && !empty($_REQUEST['displayOrder']) ? $_REQUEST['displayOrder']:'';
			if($d_name && $d_id){
				@DB::update("dictionary", array("d_name"=>$d_name,"d_order"=>$d_order,"d_type"=>$d_type,"modify_time"=>TIMESTAMP), array("d_id" => $d_id));
                //是否更新机构学校
                $school_type = isset($_REQUEST['school_type']) && !empty($_REQUEST['school_type']) ? $_REQUEST['school_type']:'';
                if(1==$d_type && !empty($school_type)){
                    //DEBUG 判断是否存在学校数据没有的话 插入 有则更新
                    $sql = "SELECT d_parent_id FROM ".DB::table('dictionary')." WHERE d_id='".$d_id."' LIMIT 1";
                    $d_parent_id = DB::result_first($sql);
                    $sql = "SELECT school_key FROM ".DB::table('school')." WHERE d_id='".$d_id."' LIMIT 1";
                    $result = DB::result_first($sql);
                    if(empty($result)){
                        //DEBUG 插入school
                        $area = $action_class->get_tree_path_id($d_parent_id);
                        $school_data = array(
                            'd_id'=>$d_id,
                            'school_intro'=>'',
                            'school_contact'=>'',
                            'school_grade'=>'',
                            'school_img'=>'',
                            'school_status'=>1,
                            'school_view'=>0,
                            'school_files_num'=>0,
                            'school_type'=>$school_type,
                            'school_domain'=>'',
                            'create_dateline'=>TIMESTAMP,
                            'modify_dateline'=>TIMESTAMP,
                            'area_id1' => isset($area[1]) ? $area[1]:0,
                            'area_id2'=> isset($area[2]) ? $area[2]:0,
                            'area_id3'=> isset($area[3]) ? $area[3]:0,
                        );
                        $insert_id = DB::insert('school',$school_data, true);
                    }else{
                        //DEBUG 更新school
                        $area = $action_class->get_tree_path_id($d_parent_id);
                        $area_id1 = isset($area[1]) ? $area[1]:0;
                        $area_id2 = isset($area[2]) ? $area[2]:0;
                        $area_id3 = isset($area[3]) ? $area[3]:0;
                        @DB::update("school", array("school_type"=>$school_type,"modify_dateline"=>TIMESTAMP,'area_id1'=>$area_id1,'area_id2'=>$area_id2,'area_id3'=>$area_id3), array("d_id" => $d_id));
                    }
                }
				$action_class->return_json(false,"操作成功");
			}else{
				$action_class->return_json(true,"操作失败");
			}
		}else{
			//DEBUG 取出一个对象信息
			$d_id = isset($_REQUEST['deptId']) && !empty($_REQUEST['deptId']) ? $_REQUEST['deptId']:'';
			$info_array = $action_class->get_info($d_id);
            $school_type = '';
            if(1==$info_array['d_type']){
                $sql = "SELECT school_type FROM ".DB::table('school')." WHERE d_id='".$d_id."' LIMIT 1";
                $school_type = DB::result_first($sql);
            }
            require SITE_ROOT.'./source/function/function_grade_class.php';
            $pub_school_type = pub_school_type();
			include template('admin/hschool/dept_edit');
		}
		break;

	case "tree":
		//DEBUG 取出下级机构
		$tree_array = array();
		$d_id = !empty($_G['member']['dept_id']) ? $_G['member']['dept_id']:100;
		$d_id = isset($_REQUEST['root']) && !empty($_REQUEST['root']) ? $_REQUEST['root']:$d_id;
		$tree_sql = "SELECT d_id,d_name FROM ".DB::table('dictionary')." WHERE isdelete = 0 AND d_parent_id = '".$d_id."' AND d_type=0 ORDER BY d_order ASC";
		$tree_sql_result = DB::fetch_all($tree_sql);
		foreach($tree_sql_result AS $key => $value){
			$tree_array[$key]['id'] = $value['d_id'];
			$tree_array[$key]['text'] = $value['d_name'];
			$tree_array[$key]['uid'] = 1;
			//DEBUG 查询是否有子节点
			$hasChildren_sql = "SELECT d_id FROM ".DB::table('dictionary')." WHERE d_parent_id = '".$value['d_id']."' LIMIT 1";
			$hasChildren_sql_result = DB::result_first($tree_sql);
			if($hasChildren_sql_result){
				$tree_array[$key]['hasChildren'] = true;
			}else{
				$tree_array[$key]['hasChildren'] = false;
			}
		}
		$tree_json = json_encode($tree_array);
		include template('admin/hschool/dept_tree');
		break;

	case "user_list":
		$d_id_array=array();
		$d_id = isset($_REQUEST['d_id']) && !empty($_REQUEST['d_id']) ? $_REQUEST['d_id']:$_G['dept_id'];
		$d_id_array = $action_class->get_sub_tree($d_id);
		if(empty($d_id_array)){
			$d_id_array=array($d_id);
		}else{
			//DEBUG 前端递归输出
			$d_id_array=array_keys($action_class->tree2array($d_id_array));
		}
		//DEBUG 取出所有单位成员
        $page_array = array();
        $sqlcount = $sql = $wheresql = $user_realname = $user_id = $pageNum = $numPerPage = '';
        $pageNum = isset($_REQUEST['pageNum']) ? $_REQUEST['pageNum'] : 1;
        $numPerPage = isset($_REQUEST['numPerPage']) ? $_REQUEST['numPerPage'] : 80;
        $pagestart = ($pageNum - 1) * $numPerPage;
		$user_realname = isset($_REQUEST['realname']) ? $_REQUEST['realname'] : '';
		$user_id = isset($_REQUEST['sequence']) ? $_REQUEST['sequence'] : '';
		//DEBUG 机构
		if($d_id_array && empty($user_id)){
			$wheresql .= " AND dept_id IN (".dimplode($d_id_array).")";
		}
		if($user_realname){
			$wheresql .= " AND user_realname = '".$user_realname."' ";
		}
		if($user_id){
			$wheresql .= " AND user_id = '".$user_id."' ";
		}
        $sqlcount = "SELECT count(*) from ".DB::table('users')." AS u WHERE u.isdelete=0 ".$wheresql;
        $pagetotal = DB::result_first($sqlcount);
        $sql = "SELECT u.* from ".DB::table('users')." AS u WHERE u.isdelete=0 ".$wheresql." ORDER BY u.user_id DESC LIMIT ".$pagestart.",".$numPerPage;
        $page_array = DB::fetch_all($sql);
		/*
		//TODO 前段JS支持
		//DEBUG 总页数
		$realpages = @ceil($pagetotal / $numPerPage);
		if($realpages <= 0){
			$realpages=1;
		}
		//DEBUG 前一页
		$page_pre = max(1, intval(($pageNum-1)));
		//DEBUG 后一页
		$page_next = min(intval(($pageNum+1)), $realpages);
		*/
		//DEBUG 加载模板
		foreach($page_array AS $key => $value){
			$page_array[$key]['d_name'] = ext::d_name($value['dept_id']);
		}
        $d_id_array_string = implode(',',$d_id_array);
		include template('admin/hschool/dept_user_list');
		break;

	case "index":
		
		include template('admin/hschool/dept');
		break;
	case "cache_reset":
		$d_id_array = $action_class->get_sub_tree(100,0);
        $data = $data_school = $data_school_class = "";
        $i=1;
        $i_max=count($d_id_array);
        foreach ( $d_id_array as $key=>$value)
        {
            if($i < $i_max){
                $dot_1=',';
            }else{
                $dot_1='';
            }
            $data = $data_school = $data_school_class .= '{"v": "'.$value["d_id"].'", "n": "'.$value["d_name"].'", "s": [';
                    $ii=1;
                    $ii_max=count($value["children"]);
                    foreach ( $value["children"] as $kk=>$vv)
                    {
                        if($ii < $ii_max){
                            $dot_2=",";
                        }else{
                            $dot_2="";
                        }
                        $data = $data_school = $data_school_class .= '{"v": "'.$vv["d_id"].'", "n": "'.$vv["d_name"].'", "s": [';
                                $iii=1;
                                $iii_max=count($vv["children"]);
                                foreach ( $vv["children"] as $k=>$v)
                                {
                                    if($iii < $iii_max){
                                        $dot_3=",";
                                    }else{
                                        $dot_3="";
                                    }
                                    $data = $data_school = $data_school_class .= '{"v":"'.$v["d_id"].'","n": "'.$v["d_name"].'", "s": [';
                                    //DEBUG 取出学校至于筛选缓存
                                    $sql = "SELECT d.d_id,d.d_name FROM ".DB::table('school')." AS s LEFT JOIN ".DB::table('dictionary')." AS d ON s.d_id=d.d_id WHERE s.area_id1='".$value["d_id"]."' AND s.area_id2='".$vv["d_id"]."' AND s.area_id3='".$v["d_id"]."' AND d_type=1";
                                    $school_result = DB::fetch_all($sql);
                                    if($school_result){
                                        $iiii=1;
                                        $iiii_max=count($school_result);
                                        foreach($school_result AS $ks => $vs){
                                            if($iiii < $iiii_max){
                                                $dot_4=",";
                                            }else{
                                                $dot_4="";
                                            }
                                            $data_school = $data_school_class .= '{"v":"'.$vs['d_id'].'","n": "'.$vs['d_name'].'"';
                                            //DEBUG 取出学校的班级
                                            $sql_class = "SELECT class_id, class_name FROM ".DB::table('class')." WHERE isdelete=0 AND dept_id= '".$vs['d_id']."' AND class_graduate = 0 LIMIT 100";
                                            $school_class_result = DB::fetch_all($sql_class);
                                            if($school_class_result){
                                                $iiiii=1;
                                                $iiiii_max=count($school_class_result);
                                                $data_school_class .= ',"s": [';
                                                foreach($school_class_result AS $kks => $vvs){
                                                    if($iiiii < $iiiii_max){
                                                        $dot_5=",";
                                                    }else{
                                                        $dot_5="";
                                                    }
                                                    $data_school_class .= '{"v":"'.$vvs['class_id'].'","n": "'.$vvs['class_name'].'"}'.$dot_5;
                                                    $iiiii++;
                                                }
                                                $data_school_class .= ']';
                                            }else{
                                                $data_school_class .= ',"s": []';
                                            }
                                            $data_school = $data_school_class .= '}'.$dot_4.'';
                                            $iiii++;
                                        }
                                    }
                                    $data = $data_school = $data_school_class .= ']}'.$dot_3.'';
                                    $iii++;
                                }
                        $data = $data_school = $data_school_class .= "]}".$dot_2."";
                        $ii++;
                    }
            $data = $data_school = $data_school_class .= "]}".$dot_1."";
            $i++;
        }
        $data = '['.trim($data, ',').']';
        $data_school = '['.trim($data_school, ',').']';
        $data_school_class = '['.trim($data_school_class, ',').']';
        $dir = SITE_ROOT.'./data/sysdata/';
        if (!is_dir($dir)) {
            dmkdir($dir, 0777);
        }
        @file_put_contents(SITE_ROOT.'data/sysdata/area.json',$data);
        @sleep(1);
        @file_put_contents(SITE_ROOT.'data/sysdata/area_school.json',$data_school);
        @sleep(1);
        @file_put_contents(SITE_ROOT.'data/sysdata/area_school_class.json',$data_school_class);
        @sleep(1);
        //DEBUG 兼容缓存 后期统计页面改版后需删除 开始
        foreach($d_id_array AS $k => $v){
			foreach($v['children'] AS $kk => $vv){
				foreach($vv['children'] AS $kkk => $vvv){
					foreach($vvv['children'] AS $kkkk => $vvvv){
						//DEBUG 目前固定学校处在第四级 level=4
						//DEBUG 取出学校下的班级
						$sql = "SELECT class_id,class_name FROM ".DB::table('class')." WHERE dept_id='".$vvvv['d_id']."' ORDER BY grade_num,class_num ASC";
						$result= DB::fetch_all($sql);
						$d_id_array[$k]['children'][$kk]['children'][$kkk]['children'][$kkkk]['class_array']=$result;
					}
				}
			}
		}
		$d_id_array_json = json_ext($d_id_array);
		@file_put_contents(SITE_ROOT.'./data/cache/dept_class.txt',$d_id_array_json);
        //DEBUG 兼容缓存 后期统计页面改版后需删除 结束
		if(file_exists(SITE_ROOT.'./data/sysdata/area.json') && file_exists(SITE_ROOT.'./data/cache/dept_class.txt')){
			$action_class->return_json(false,"操作成功");
		}else{
			$action_class->return_json(true,"操作失败");
		}
		break;

}
?>